import 'dart:async';

import 'package:flutter/services.dart';
import 'package:meta/meta.dart' show visibleForTesting;

class KmPrinter {
  factory KmPrinter() {
    if (_instance == null) {
      const MethodChannel methodChannel = const MethodChannel(METHOD_CHANNEL);
      const EventChannel eventChannel = const EventChannel(EVENT_CHANNEL);
      _instance = KmPrinter.private(methodChannel, eventChannel);
    }
    return _instance!;
  }

  @visibleForTesting
  KmPrinter.private(
    this._methodChannel,
    this._eventChannel,
  );

  static const String METHOD_CHANNEL = 'android.bluetooth.print.km/method';
  static const String EVENT_CHANNEL = 'android.bluetooth.print.km/event';

  static KmPrinter? _instance;

  final MethodChannel _methodChannel;
  final EventChannel _eventChannel;

  // final Stream _stream;

  Future<String> get platformVersion async {
    final String version =
        await _methodChannel.invokeMethod('getPlatformVersion');
    return version;
  }

  Future<Null> defaultPrinter() async {
    await _methodChannel.invokeMethod('kmSharedStorePrinter');
  }

  Future<Null> imgPrint(map) async {
    await _methodChannel.invokeMethod('kmStartPrint', map);
  }

  Future<Null> startScan() async {
    await _methodChannel.invokeMethod('kmStartScan');
  }

  Future<Null> stopScan() async {
    await _methodChannel.invokeMethod('kmStopScan');
  }

  Future<Null> openPrinter(deviceMap) async {
    await _methodChannel.invokeMethod('kmOpenPrinter', deviceMap);
  }

  Future<Null> connAndOpen(deviceMap) async {
    await _methodChannel.invokeMethod('kmConnAndOpen', deviceMap);
  }

  Future<Null> changeBlueName(deviceMap) async {
    await _methodChannel.invokeMethod('kmChangeBlueName', deviceMap);
  }

  Stream get kmReceiver {
    return _eventChannel.receiveBroadcastStream().map((value) => value);
  }
}
